import React from "react";
import { InternalToast } from "antd-mobile/es/components/toast/toast";
import { renderImperatively } from "antd-mobile/es/utils/render-imperatively";
import { mergeProps } from "src/utils";

/**
 * 修改antd-mobile toast 支持点击关闭
 * 后期版本支持可替换
 */

let currentHandler = null;
let currentTimeout = null;

const defaultProps = {
    duration: 2000,
    position: "center",
    maskClickable: true,
    stopPropagation: [],
};

const ToastInner = props => {
    return (
        <div
            onClick={e => {
                clear();
            }}
            style={{ width: "100vw", height: "100vh", position: "fixed", top: 0, left: 0 }}
        >
            <InternalToast {...props} />
        </div>
    );
};

export function show(p) {
    const props = mergeProps(defaultProps, typeof p === "string" ? { content: p } : p);
    const element = (
        <ToastInner
            {...props}
            onClose={() => {
                currentHandler = null;
            }}
        />
    );
    if (currentHandler) {
        currentHandler.replace(element);
    } else {
        currentHandler = renderImperatively(element);
    }

    if (currentTimeout) {
        window.clearTimeout(currentTimeout);
    }
    if (props.duration !== 0) {
        currentTimeout = window.setTimeout(() => {
            clear();
        }, props.duration);
    }

    return currentHandler;
}

export function clear() {
    currentHandler?.close();
    currentHandler = null;
}

export function config(val) {
    if (val.duration !== undefined) {
        defaultProps.duration = val.duration;
    }
    if (val.position !== undefined) {
        defaultProps.position = val.position;
    }
    if (val.maskClickable !== undefined) {
        defaultProps.maskClickable = val.maskClickable;
    }
}

const clickToast = {
    show,
    clear,
    config,
};

export default clickToast;
